package software.hust.com.hust_last.view;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ZoomControls;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.poi.PoiSearch;

import software.hust.com.hust_last.MyApplication;
import software.hust.com.hust_last.R;

public class MainActivity extends Activity implements
        BaiduMap.OnMarkerClickListener, BaiduMap.OnMapClickListener, View.OnClickListener {
    private MapView mMapView = null;
    private GeoCoder mSearch;
    private BaiduMap mBaiduMap;
    private PoiSearch mPoiSearch = null;
    private LocationClient mLocClient;
    private MyLocationListenner myListener = new MyLocationListenner();
    private LocationClientOption option;
    private BDLocation mapLocation;
    // 自身定位地址
    private MyLocationData locData;
    // 是否首次定位
    private boolean isFirstLoc = true;
    private Button treasure_bt_dig;
    // 标记是否显示屏幕中的红色img
    private boolean showAddFlag = false;
    private ImageView treasure_pin_iv;

    private static final int BAIDU_READ_PHONE_STATE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //在使用SDK各组件之前初始化context信息，传入ApplicationContext
        //注意该方法要再setContentView方法之前实现
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.bmapView);
        treasure_bt_dig = (Button) findViewById(R.id.treasure_bt_dig);
        treasure_pin_iv = (ImageView) findViewById(R.id.treasure_pin_iv);
        treasure_bt_dig.setOnClickListener(this);
        treasure_pin_iv.setOnClickListener(this);
        mBaiduMap = mMapView.getMap();
        initMap();
        if (Build.VERSION.SDK_INT >= 23) {
            showContacts();
        } else {
            location();//init为定位方法
        }
    }

    private void initMap() {
        /**
         * 设置地图初始化时缩放尺寸
         */
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);
        mBaiduMap.setMapStatus(msu);

        int count = mMapView.getChildCount();
        for (int i = 0; i < count; i++) {
            View child = mMapView.getChildAt(i);

            if (child instanceof ZoomControls) {
                child.setVisibility(View.INVISIBLE);
            }
        }
    }

    private void location() {
        mSearch = GeoCoder.newInstance();
        // mSearch.setOnGetGeoCodeResultListener(listener);

        mBaiduMap.setMyLocationEnabled(true);
        // 初始化搜索模块，注册搜索事件监听
        mPoiSearch = PoiSearch.newInstance();
        // 设置覆盖物点击监听
        mBaiduMap.setOnMarkerClickListener(this);
        // 监听地图单击事件，以进行覆盖物创建
        mBaiduMap.setOnMapClickListener(this);
        // 删除百度地图LoGo
        mMapView.removeViewAt(1);
        //删除放大缩小按钮
        mMapView.showZoomControls(false);
        // 定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);// 设置定位模式
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setIsNeedAddress(true);
        // 设置定位刷新时间
        option.setScanSpan(20000);
        mLocClient.setLocOption(option);
        mLocClient.start();

    }

    @Override
    public void onMapClick(LatLng latLng) {

    }

    @Override
    public boolean onMapPoiClick(MapPoi mapPoi) {
        return false;
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.treasure_bt_dig:
                // 是否显示中心标示
                if (showAddFlag) {
                    showAddFlag = false;
                    treasure_pin_iv.setVisibility(View.GONE);
                } else {
                    showAddFlag = true;
                    treasure_pin_iv.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.treasure_pin_iv:
                // 获得选中点的经纬度坐标
                LatLng ptCenter = new LatLng(
                        mBaiduMap.getMapStatus().target.latitude,
                        mBaiduMap.getMapStatus().target.longitude);
                MyApplication.mApplication.CreateTreasureLatLng = ptCenter;
                // 进行页面跳转，到新建宝藏界面
                Intent intent = new Intent();
                intent.setClass(getApplicationContext(), AddTreasureActivity.class);
                intent.putExtra("ptCenter", ptCenter);
                startActivity(intent);
                intent = null;
                break;

        }
    }

    class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置

            if (location == null || mMapView == null) {
                return;
            }
            startLocation(location);
            mapLocation = location;

            MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(new LatLng(
                    location.getLatitude(), location.getLongitude()));
            mBaiduMap.animateMapStatus(u);
        }
    }
//

    /**
     * @param location
     * @des 开启自身定位
     */
    private void startLocation(BDLocation location) {
        locData = new MyLocationData.Builder().accuracy(location.getRadius())
                // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(0).latitude(location.getLatitude())
                .longitude(location.getLongitude()).build();
        mBaiduMap.setMyLocationData(locData);
        if (isFirstLoc) {
            isFirstLoc = false;
            LatLng ll = new LatLng(location.getLatitude(),
                    location.getLongitude());
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(ll).zoom(15.0f);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory
                    .newMapStatus(builder.build()));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    public void showContacts() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(getApplicationContext(), "没有权限,请手动开启定位权限", Toast.LENGTH_SHORT).show();
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE}, BAIDU_READ_PHONE_STATE);
        } else {
            location();
        }
    }


    //Android6.0申请权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case BAIDU_READ_PHONE_STATE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                    location();
                } else {
                    // 没有获取到权限，做特殊处理
                    Toast.makeText(getApplicationContext(), "获取位置权限失败，请手动开启", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }
}
